package com.woyou.fragment.order;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.jing.biandang.R;
import com.woyou.activity.HomeActivity;
import com.woyou.adapter.InvalidOrderAdapter;
import com.woyou.adapter.SearchOrderAdapter;
import com.woyou.adapter.SendedOrderAdapter;
import com.woyou.adapter.SuperViewPagerAdapter;
import com.woyou.adapter.UnsendOrderAdapter;
import com.woyou.adapter.UnsendOrderAdapter.SendOrderImpl;
import com.woyou.bean.Order;
import com.woyou.bean.WYList;
import com.woyou.bean.rpc.SendOrderRes;
import com.woyou.component.AllSentView;
import com.woyou.component.NoOrderView;
import com.woyou.component.OrderNavigationView;
import com.woyou.component.SuperUI;
import com.woyou.component.WaitPersonView;
import com.woyou.controller.OrderController;
import com.woyou.event.EventSendOrder;
import com.woyou.fragment.SuperFragment;
import com.woyou.fragment.order.NewOrderFragment.RefreshOrderImpl;
import com.woyou.listener.OrderPageChangeListener;
import com.woyou.model.OrderManageModel;
import com.woyou.model.rpc.OrderModel;
import com.woyou.utils.TypeJudgeTools;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import de.greenrobot.event.EventBus;
/**
 * 
 * 订单Fragment
 * @author xuron 
 * @versionCode 1 <每次修改提交前+1>
 */
public class OrderFragment extends SuperFragment implements OnClickListener, SendOrderImpl, RefreshOrderImpl {
	private HomeActivity homeActivity;
	/**
	 * 订单控制器
	 */
	public OrderController orderController;
	public InputMethodManager imm;
	private View layout_order;
	// 导航栏
	private OrderNavigationView orderNavigationView;

	// viewpager
	public ViewPager layout_order_vp;
	private SuperViewPagerAdapter superViewPagerAdapter;
	private View layout_order_unsend;
	private View layout_order_sended;
	private View layout_order_invalid;
	private View layout_order_search;

	// 今日无订单页面
	public NoOrderView noOrderView;
	// 全部送出
	public AllSentView allSentView;

	// 订单控制器
	public OrderManageModel omModel = OrderManageModel.getInstance();
	public OrderModel orderModel;
	// 等待人数
	public WaitPersonView waitPersonView;
	// 未送出订单
	public RelativeLayout layout_order_hasorder;
	private ListView layout_order_unsend_lv;
	public UnsendOrderAdapter unsendOrderAdapter;
	public List<Order> unsendData = new ArrayList<Order>();

	// 已送出订单
	public ListView layout_order_sended_lv;
	public SendedOrderAdapter sendedOrderAdapter;
	public List<Order> sendData = new ArrayList<Order>();

	// 无效订单
	public ListView layout_order_invalid_lv;
	public InvalidOrderAdapter invalidOrderAdapter;
	public List<Order> invalidData = new ArrayList<Order>();

	// 搜索订单
	public ListView layout_order_search_lv;
	public SearchOrderAdapter searchOrderAdapter;
	public List<Order> searchData = new ArrayList<Order>();
	public EditText layout_order_search_et;
	private ImageView layout_order_search_clear;
	private String keyWord = "";

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
		layout_order = inflater.inflate(R.layout.layout_order, container, false);
		homeActivity=(HomeActivity)getActivity();
		orderController = new OrderController(homeActivity);
		orderModel = OrderModel.getInstance(homeActivity);
		return layout_order;
	}

	@Override
	public void onPause() {
		super.onPause();
		EventBus.getDefault().unregister(this);
	}

	@Override
	public void onResume() {
		super.onResume();
		EventBus.getDefault().register(this);
	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		if (!hidden) {
			// 判断是否显示输入法，如果当前页面是搜索页面则显示，反之则反
			if (layout_order_vp.getCurrentItem() == 3) {
				layout_order_search_et.requestFocus();
				imm.showSoftInput(layout_order_search_et, InputMethodManager.SHOW_IMPLICIT);
			} else {
				homeActivity.hideInputMethod();
			}

			// 刷新搜索订单,当前页面是搜索订单页面
			if (layout_order_vp.getCurrentItem() == 3) {
				keyWord = layout_order_search_et.getText().toString();
				if (!TypeJudgeTools.isNull(keyWord)) {
					orderController.refreshSearchData(keyWord);
					layout_order_search_clear.setVisibility(View.VISIBLE);
				} else {
					layout_order_search_clear.setVisibility(View.GONE);
					searchData.clear();
					searchOrderAdapter.notifyDataSetChanged();
				}
			}

			// 刷新今日无订单页面
			if (noOrderView.getVisibility() == View.VISIBLE) {
				noOrderView.showNoOrderView();
			}
			// 刷新今日订单全部送出页面
			if (allSentView.getVisibility() == View.VISIBLE) {
				allSentView.showAllSendOrderView();
			}

		}
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		// 初始化Viewpager
		layout_order_vp = (ViewPager) layout_order.findViewById(R.id.layout_order_vp);
		// 初始化导航条
		orderNavigationView = (OrderNavigationView) layout_order.findViewById(R.id.layout_ordernavigation);
		orderNavigationView.refreshView(homeActivity, layout_order_vp);
		List<View> views = new ArrayList<View>();
		layout_order_unsend = View.inflate(homeActivity,R.layout.layout_order_unsend, null);
		layout_order_sended = View.inflate(homeActivity,R.layout.layout_order_sended, null);
		layout_order_invalid = View.inflate(homeActivity,R.layout.layout_order_invalid, null);
		layout_order_search = View.inflate(homeActivity,R.layout.layout_order_search, null);

		views.add(layout_order_unsend);
		views.add(layout_order_sended);
		views.add(layout_order_invalid);
		views.add(layout_order_search);
	
		// 今日无任何订单页面
		initNoOrderData();
		// 未送出订单
		initUnsendData();
		// 已送出订单
		initSendedData();
		// 无效订单
		initInvalidData();
		// 搜索订单
		initSearchData();
		// 加载所有数据
		orderController.loadAllOrderList();
		//
		superViewPagerAdapter = new SuperViewPagerAdapter(views);
		layout_order_vp.setAdapter(superViewPagerAdapter);
		layout_order_vp.setOnPageChangeListener(new OrderPageChangeListener(homeActivity, imm, layout_order_search_et,
				orderNavigationView.screenWidth, orderNavigationView.layout_order_navi_iv));
	}

	/**
	 * 初始化今日无订单页面
	 */
	public void initNoOrderData() {
		noOrderView = (NoOrderView) layout_order.findViewById(R.id.layout_noorder);
		noOrderView.setParams(homeActivity, this, orderModel);
	}

	/**
	 * 设配未送出订单和送完订单
	 */
	public void initUnsendData() {
		// 全部送完
		allSentView = (AllSentView) layout_order_unsend.findViewById(R.id.layout_allsentview);
		allSentView.setParams(homeActivity, this, orderModel, omModel);
		// 等待人数
		waitPersonView = (WaitPersonView) layout_order_unsend.findViewById(R.id.layout_waitpersonview);
		waitPersonView.setParams(omModel);
		// 未送订单列表
		layout_order_hasorder = (RelativeLayout) layout_order_unsend.findViewById(R.id.layout_order_hasorder);
		layout_order_unsend_lv = (ListView) layout_order_unsend.findViewById(R.id.layout_order_unsend_lv);
		unsendOrderAdapter = new UnsendOrderAdapter(homeActivity, this, unsendData);
		layout_order_unsend_lv.addFooterView(LayoutInflater.from(homeActivity).inflate(R.layout.item_order_footer_lv, null));
		layout_order_unsend_lv.setAdapter(unsendOrderAdapter);
		// 定时刷新本地数据
		orderController.refreshLocationOrder();
	}

	/**
	 * 送出订单
	 */
	public void onEvent(EventSendOrder event) {
		SendOrderRes res = event.getSendOrderRes();
		omModel.moveOrder2SentList(res.getoId(), res.getSendTime(), res.getStatus());
		orderController.refreshUnsendData();
		orderController.refreshSendData();
		orderController.switchPanel();
	}

	/**
	 * 实现的SendOrderImpl接口处理送出订单事件 设置未送订单和已送订单的内容并且重新刷新页面
	 */
	@Override
	public void HandleSendOrder() {
		orderController.refreshUnsendData();
		orderController.refreshSendData();
	}

	// 设配已送出订单
	public void initSendedData() {
		layout_order_sended_lv = (ListView) layout_order_sended.findViewById(R.id.layout_order_sended_lv);
		sendedOrderAdapter = new SendedOrderAdapter(getActivity(), sendData);
		layout_order_sended_lv.setAdapter(sendedOrderAdapter);
		layout_order_sended_lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				// 将已送出订单信息存储到ACache中
				WYList<HashMap<String, String>> orderList = new WYList<HashMap<String, String>>();
				HashMap<String, String> map;
				for (int i = 0; i < sendData.size(); i++) {
					map = new HashMap<String, String>();
					map.put("No", sendData.get(i).getoId());
					orderList.add(map);
				}
				// 存储已送订单信息和点击item的位置信息
				aCache.put("OrderList", orderList);
				aCache.put("Position", position + "");
				// 先获取订单详情再跳转到订单详情页面
				orderController.jumpToOrderDetails(position, orderList);
			}
		});
	}

	// 适配无效订单
	public void initInvalidData() {
		layout_order_invalid_lv = (ListView) layout_order_invalid.findViewById(R.id.layout_order_invalid_lv);
		invalidOrderAdapter = new InvalidOrderAdapter(getActivity(), invalidData);
		layout_order_invalid_lv.setAdapter(invalidOrderAdapter);

		layout_order_invalid_lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				// 将无效订单信息存储到ACache中
				WYList<HashMap<String, String>> orderList = new WYList<HashMap<String, String>>();
				HashMap<String, String> map;
				for (int i = 0; i < invalidData.size(); i++) {
					map = new HashMap<String, String>();
					map.put("No", invalidData.get(i).getoId());
					orderList.add(map);
				}
				// 存储无效订单信息和点击item的位置信息
				aCache.put("OrderList", orderList);
				aCache.put("Position", position + "");

				// 先获取订单详情再跳转到订单详情页面
				orderController.jumpToOrderDetails(position, orderList);
			}

		});
	}

	// 搜索订单
	public void initSearchData() {
		layout_order_search_et = (EditText) layout_order_search.findViewById(R.id.layout_order_search_et);

		// 清除搜索框的内容
		layout_order_search_clear = (ImageView) layout_order_search.findViewById(R.id.layout_order_search_clear);
		layout_order_search_clear.setOnClickListener(this);
		layout_order_search_lv = (ListView) layout_order_search.findViewById(R.id.layout_order_search_lv);
		searchOrderAdapter = new SearchOrderAdapter(getActivity(), searchData);
		layout_order_search_lv.setAdapter(searchOrderAdapter);

		layout_order_search_lv.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				// 将未送出订单信息存储到ACache中
				WYList<HashMap<String, String>> orderList = new WYList<HashMap<String, String>>();
				HashMap<String, String> map;
				for (int i = 0; i < searchData.size(); i++) {
					map = new HashMap<String, String>();
					map.put("No", searchData.get(i).getoId());
					orderList.add(map);
				}
				// 存储未送订单信息和点击item的位置信息
				aCache.put("OrderList", orderList);
				aCache.put("Position", position + "");

				// 先获取订单详情再跳转到订单详情页面
				orderController.jumpToOrderDetails(position, orderList);
			}
		});

		// 监听输入框文字的变化并执行搜索
		layout_order_search_et.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				keyWord = layout_order_search_et.getText().toString();
				if (!TypeJudgeTools.isNull(keyWord)) {
					orderController.refreshSearchData(keyWord);
					layout_order_search_clear.setVisibility(View.VISIBLE);
				} else {
					SuperUI.openToast(homeActivity, "请输入关键字");
					layout_order_search_clear.setVisibility(View.GONE);
					searchData.clear();
					searchOrderAdapter.notifyDataSetChanged();
				}

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.layout_order_search_clear:
			layout_order_search_et.setText("");
			break;
		}
	}

	/**
	 * 实现NewOrderFragment的更新未送订单的接口
	 */
	@Override
	public void refreshUnSendOrder() {
		orderController.refreshUnsendData();
	}

	/**
	 * 实现NewOrderFragment的更新无效订单的接口
	 */
	@Override
	public void refreshInvalidOrder() {
		orderController.refreshInvalidData();
		// 隐藏无订单页面
		homeActivity.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				noOrderView.setVisibility(View.GONE);
			}
		});
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		// 关闭刷新Timer
		orderController.onDestroy();
	}
}
